package handlers

import (
	"errors"
	"html/template"
	"strconv"
	"strings"

	"github.com/yjp211/web"

	"mutu/misc/typedef"
	"mutu/models"
	"mutu/service"
)

type BinderView struct{}

var (
	BinderHandler = BinderView{}
)

func (p BinderView) CreateIndex(ctx *web.Context) {
	tags, _ := service.TagService.GetAllTags()
	cats, _ := service.CategoryService.GetAllCategorys()

	data := typedef.Dict{
		"tags": tags,
		"cats": cats,
	}
	t, _ := template.ParseFiles("templates/binder-create.html")
	t.Execute(ctx, data)
}

func (p BinderView) ManageIndex(ctx *web.Context) {

	ses := ctx.Dict["session"].(*models.Session)
	binders, _ := service.BinderService.GetUserBinders(ses.UserId)
	data := typedef.Dict{
		"binders": binders,
	}
	t, _ := template.ParseFiles("templates/binder-manage.html")
	t.Execute(ctx, data)
}

func (p BinderView) ManageIndex2(ctx *web.Context) {

	ses := ctx.Dict["session"].(*models.Session)
	arr, _ := service.BinderService.GetItems(ses.UserId, ses.UserId, 0)

	service.MatterService.FillMattersInfo(arr, true, false, false, false)
	data := typedef.Dict{
		"matters": arr,
	}
	t, _ := template.ParseFiles("templates/binder-manage2.html")
	t.Execute(ctx, data)
}

func (p BinderView) EditIndex(ctx *web.Context) {

	uuid, ok := ctx.Params["uuid"]
	if !ok {
		ctx.Abort(401, "参数错误")
		return
	}
	binder, err := service.BinderService.GetBinderByUuid(uuid)
	if err != nil {
		ctx.Abort(500, err.Error())
		return
	}
	ses := ctx.Dict["session"].(*models.Session)
	if ses.UserId != binder.UserId {
		ctx.Abort(403, "没有权限")
		return
	}
	tags, _ := service.TagService.GetAllTags()
	cats, _ := service.CategoryService.GetAllCategorys()
	data := typedef.Dict{
		"cats":       cats,
		"tags":       tags,
		"binder":     binder,
		"binderJson": PureJson(binder),
	}
	t, _ := template.ParseFiles("templates/binder-edit.html")
	t.Execute(ctx, data)
}

func (p BinderView) Create(ctx *web.Context) string {
	cat, err := strconv.Atoi(ctx.Params["categroy"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	tagstr, _ := ctx.Params["tags"]
	arr := strings.Split(tagstr, ",")
	tags := []int{}
	for _, item := range arr {
		tag, err := strconv.Atoi(item)
		if err == nil {
			tags = append(tags, tag)
		}
	}
	if len(tags) == 0 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	title, ok1 := ctx.Params["title"]
	desc, ok2 := ctx.Params["desc"]
	isPubStr, ok3 := ctx.Params["ispub"]
	if !ok1 || !ok2 || !ok3 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	var ispub = true
	if isPubStr != "1" {
		ispub = false
	}

	ses := ctx.Dict["session"].(*models.Session)

	binder := &models.Binder{
		Title:  title,
		Desc:   desc,
		IsPub:  ispub,
		UserId: ses.UserId,
	}
	err = service.BinderService.CreateBinder(cat, tags, binder)
	return JsonpReturn(ctx, nil, err)

}

func (p BinderView) Edit(ctx *web.Context) string {
	uuid, ok := ctx.Params["uuid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	cat, err := strconv.Atoi(ctx.Params["categroy"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	tagstr, _ := ctx.Params["tags"]
	arr := strings.Split(tagstr, ",")
	tags := []int{}
	for _, item := range arr {
		tag, err := strconv.Atoi(item)
		if err == nil {
			tags = append(tags, tag)
		}
	}
	if len(tags) == 0 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	title, ok1 := ctx.Params["title"]
	desc, ok2 := ctx.Params["desc"]
	isPubStr, ok3 := ctx.Params["ispub"]
	if !ok1 || !ok2 || !ok3 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	var ispub = true
	if isPubStr != "1" {
		ispub = false
	}

	ses := ctx.Dict["session"].(*models.Session)

	binder := &models.Binder{
		Uuid:   uuid,
		Title:  title,
		Desc:   desc,
		IsPub:  ispub,
		UserId: ses.UserId,
	}
	err = service.BinderService.EditBinder(cat, tags, binder)
	return JsonpReturn(ctx, nil, err)

}

func (p BinderView) Delete(ctx *web.Context) string {
	uuid, ok := ctx.Params["uuid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	ses := ctx.Dict["session"].(*models.Session)

	err := service.BinderService.DeleteBinder(ses.UserId, uuid)

	return JsonpReturn(ctx, nil, err)
}

func (p BinderView) AddItem(ctx *web.Context) string {

	ses := ctx.Dict["session"].(*models.Session)

	binderid, ok := ctx.Params["binderid"]
	if !ok {
		//return JsonpReturn(ctx, nil, errors.New("参数错误"))
		binderid = ses.UserId
	}

	matterid, ok := ctx.Params["matterid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	err := service.BinderService.AddItem(ses.UserId, binderid, matterid)

	return JsonpReturn(ctx, nil, err)
}

func (p BinderView) RemoveItem(ctx *web.Context) string {

	ses := ctx.Dict["session"].(*models.Session)

	binderid, ok := ctx.Params["binderid"]
	if !ok {
		//return JsonpReturn(ctx, nil, errors.New("参数错误"))
		binderid = ses.UserId
	}

	matterid, ok := ctx.Params["matterid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	err := service.BinderService.RemoveItem(ses.UserId, binderid, matterid)

	return JsonpReturn(ctx, nil, err)
}

func (p BinderView) GetItems(ctx *web.Context) string {

	ses := ctx.Dict["session"].(*models.Session)

	binderid, ok := ctx.Params["binderid"]
	if !ok {
		//return JsonpReturn(ctx, nil, errors.New("参数错误"))
		binderid = ses.UserId
	}

	arr, err := service.BinderService.GetItems(ses.UserId, binderid, 0)
	if err != nil {
		return JsonpReturn(ctx, nil, err)
	}
	service.MatterService.FillMattersInfo(arr, true, false, false, false)
	data := typedef.Dict{
		"matters": arr,
	}
	return JsonpReturn(ctx, data, nil)
}
